//
//  ThemeCompatible.swift
//  ACFrameworkSwift
//
//  Created by c5342925 on 2022/6/3.
//

import Foundation

// MARK: - ThemeWrapper

public struct ThemeWrapper<Base> {
    public let base: Base
    init(_ base: Base) {
        self.base = base
    }
}

// MARK: - ThemeCompatible

public protocol ThemeCompatible: AnyObject { }
public extension ThemeCompatible {
    var theme: ThemeWrapper<Self> {
        get { return ThemeWrapper<Self>(self) }
        set { }
    }
}

extension UIView: ThemeCompatible { }
extension CALayer: ThemeCompatible {  }
extension UIBarItem: ThemeCompatible {  }

// MARK: - UIView

public extension ThemeWrapper where Base: UIView {
    
    /// The backgroundColor of theme.
    var backgroundColor: UIColor? {
        get {
            return base.backgroundColor
        }
        set {
            var newColor = newValue
            if let colorProvider = newColor?.themeProvider {
                let key = "\(#function)"
                let closure: (ACThemeStyle) -> Void = { [weak base] theme in
                    base?.backgroundColor = colorProvider(theme)
                }
                base.providers[key] = closure
                newColor = colorProvider(ACThemeManager.share.currentTheme)
            }
            base.backgroundColor = newColor
        }
    }
    
}

// MARK: - UILabel

public extension ThemeWrapper where Base: UILabel {
    
    /// The textColor of theme.
    var textColor: UIColor? {
        get {
            return base.textColor
        }
        set {
            var newColor = newValue
            if let colorProvider = newColor?.themeProvider {
                let key = "\(#function)"
                let closure: (ACThemeStyle) -> Void = { [weak base] theme in
                    base?.textColor = colorProvider(theme)
                }
                base.providers[key] = closure
                newColor = colorProvider(ACThemeManager.share.currentTheme)
            }
            base.textColor = newColor
        }
    }
    
}

// MARK: - UIButton

public extension ThemeWrapper where Base: UIButton {
    
    func setTitleColor(_ color: UIColor?, for state: UIControl.State) {
        var newColor = color
        if let colorProvider = newColor?.themeProvider {
            let key = "\(#function)"
            let closure: (ACThemeStyle) -> Void = { [weak base] theme in
                base?.setTitleColor(colorProvider(theme), for: state)
            }
            base.providers[key] = closure
            newColor = colorProvider(ACThemeManager.share.currentTheme)
        }
        base.setTitleColor(newColor, for: state)
    }
    
}
